﻿using DidaManager.Native.Network;
using DidaManager.Native.SerialPort;
using LiteDb;
using LiteDB;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DidaManager.Models;
using CefSharp.DevTools.Network;
using Newtonsoft.Json;
using DidaManager.Native.Download;
using System.IO;
using NLua;
using DidaManager.Native.RemoteTransmission;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace DidaManager.Native
{
    public class NativeManager
    {
        private readonly NetworkManager _networkManager;
        private readonly SerialPortManager _serialPortManager;
        private readonly DownloadManager _downloadManager;
        private readonly RemoteTransManager _remoteTransManager;


        public NativeManager(Control? invokeControl = null)
        {
            _networkManager = new NetworkManager();
            _serialPortManager = new SerialPortManager();
            _downloadManager = new DownloadManager(_serialPortManager, invokeControl);
            _remoteTransManager = new RemoteTransManager(_serialPortManager);
            DeviceHJ212Code.LoadAllSheets(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config", "hj212_code.xlsx"));
        }

#region 下载相关工具栏功能
        /// <summary>
        /// 获取本机网络适配器列表
        /// </summary>
        public object GetNativeNetworkAdapter(object param)
        {
            var networkAdapter = new NetworkAdapter();
            var networkAdapters = networkAdapter.GetNetworkAdapters();
            // 序列化为JSON字符串然后反序列化为动态对象，确保返回纯JSON格式
            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(networkAdapters);
            return ApiResponse.Success(jsonString);
        }

        /// <summary>
        /// 处理网络适配器连接
        /// </summary>
        public object HandleAdapterConnect(object param)
        {
            return _networkManager.HandleAdapterConnect(param);
        }  

        /// <summary>
        /// 获取网关设备列表
        /// </summary>
        public object GetGateWayDeviceList(object param)
        {
            return _networkManager.HandleSearchDevice(param);
        }   

        /// <summary>
        /// 获取串口列表
        /// </summary>
        public object GetSerialPortList(object param)
        {
            return _serialPortManager.GetSerialPortList(param);
        } 

        /// <summary>
        /// 打开串口
        /// </summary>
        public object OpenSerialPort(object param)
        {
            return _serialPortManager.OpenSerialPort(param);
        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        public object CloseSerialPort(object param)
        {
            return _serialPortManager.CloseSerialPort(param);
        }

        /// <summary>  
        /// 测试网络连接  
        /// </summary>  
        public object TestNetworkConnection(object param)
        {
            return _networkManager.TestNetworkConnection(param);
        }

        /// <summary>
        /// 通过串口下载配置
        /// </summary>
        public object DownloadConfigViaSerial(object param)
        {
            return _downloadManager.DownloadViaSerial(param);
        }

        /// <summary>
        /// 通过网络下载配置
        /// </summary>
        public object DownloadConfigViaNetwork(object param)
        {
            // 获取下载url
            var downloadUrl = _networkManager.GetDownloadUrl(param);
            if (string.IsNullOrEmpty(downloadUrl))
            {
                return ApiResponse.Fail("下载URL不能为空");
            }

            return _downloadManager.DownloadViaNetwork(downloadUrl);
        }

         public object StopDownload(object param)
         {
            return _downloadManager.StopDownload(param);
         }

        // 网关重启
        public object RestartGateway(object param)
        {
            return _networkManager.RestartGateway(param);
        }

        // 固件更新
        public object UpdateFirmware(object param)
        {
            return _networkManager.UpdateFirmware(param);
        }

        // 更新到服务器
        public object UpdateToServer(object param)
        {
            return _networkManager.UpdateToServer(param);
        }

        // 更新到设备
        public object UpdateToDevice(object param)
        {
            return _networkManager.UpdateToDevice(param);
        }

        // 获取设备更新状态
        public object GetDeviceUpdateStatus(object param)
        {
            return _networkManager.GetDeviceUpdateStatus(param);
        }
        
        // 获取文件路径
        public object OpenFileDialog(object param)
        {
            try
            {
                if (param == null)
                {
                    return ApiResponse.Fail("参数不能为空");
                }

                // 确保 param.ToString() 不为 null
                var paramString = param.ToString();
                if (string.IsNullOrEmpty(paramString))
                {
                    return ApiResponse.Fail("参数不能为空或空字符串");
                }

                // 反序列化 JSON
                var json = JsonConvert.DeserializeObject<dynamic>(paramString);
                if (json == null)
                {
                    return ApiResponse.Fail("参数反序列化失败");
                }

                var title = json.TryGetValue("title", out JToken? titleValue) ? titleValue?.ToString() : "选择固件文件";
                var filter = json.TryGetValue("filter", out JToken? filterValue) ? filterValue?.ToString() : "固件文件 (*.bin)|*.bin|所有文件 (*.*)|*.*";

                // 创建 OpenFileDialog
                using (var openFileDialog = new System.Windows.Forms.OpenFileDialog())
                {
                    openFileDialog.Title = title;
                    openFileDialog.Filter = filter;
                    openFileDialog.FilterIndex = 1;
                    openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    openFileDialog.Multiselect = false;
                    openFileDialog.CheckFileExists = true;
                    openFileDialog.CheckPathExists = true;

                    string selectedFilePath = string.Empty;
                    System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.DialogResult.Cancel;

                    var thread = new System.Threading.Thread(() =>
                    {
                        try
                        {
                            System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA);
                            dialogResult = openFileDialog.ShowDialog();
                            if (dialogResult == System.Windows.Forms.DialogResult.OK)
                            {
                                selectedFilePath = openFileDialog.FileName;
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"OpenFileDialog线程异常: {ex.Message}");
                        }
                    });

                    thread.SetApartmentState(System.Threading.ApartmentState.STA);
                    thread.Start();
                    thread.Join();

                    if (dialogResult == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(selectedFilePath))
                    {
                        //if (!Path.GetExtension(selectedFilePath).Equals(".bin", StringComparison.OrdinalIgnoreCase))
                        //{
                        //    return ApiResponse.Fail("请选择.bin格式的固件文件");
                        //}

                        if (!File.Exists(selectedFilePath))
                        {
                            return ApiResponse.Fail("选择的文件不存在");
                        }

                        var fileInfo = new FileInfo(selectedFilePath);
                        var result = new
                        {
                            filePath = selectedFilePath,
                            fileName = Path.GetFileName(selectedFilePath),
                            fileSize = fileInfo.Length
                        };

                        var jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(result);
                        return ApiResponse.Success(jsonResult, "文件选择成功");
                    }
                    else
                    {
                        return ApiResponse.Fail("用户取消了文件选择");
                    }
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"打开文件对话框失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 打开文件夹选择对话框
        /// </summary>
        /// <param name="param">包含title等参数的JSON字符串</param>
        /// <returns>选择的文件夹路径信息</returns>
        public object OpenFolderDialog(object param)
        {
            try
            {
                var title = "选择文件夹";
                // 创建 FolderBrowserDialog
                using (var folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    folderBrowserDialog.Description = title;
                    folderBrowserDialog.UseDescriptionForTitle = true;
                    folderBrowserDialog.ShowNewFolderButton = true;
                    folderBrowserDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                    string selectedFolderPath = string.Empty;
                    System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.DialogResult.Cancel;

                    var thread = new System.Threading.Thread(() =>
                    {
                        try
                        {
                            System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA);
                            dialogResult = folderBrowserDialog.ShowDialog();
                            if (dialogResult == System.Windows.Forms.DialogResult.OK)
                            {
                                selectedFolderPath = folderBrowserDialog.SelectedPath;
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"OpenFolderDialog线程异常: {ex.Message}");
                        }
                    });

                    thread.SetApartmentState(System.Threading.ApartmentState.STA);
                    thread.Start();
                    thread.Join();

                    if (dialogResult == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(selectedFolderPath))
                    {
                        if (!Directory.Exists(selectedFolderPath))
                        {
                            return ApiResponse.Fail("选择的文件夹不存在");
                        }

                        var directoryInfo = new DirectoryInfo(selectedFolderPath);
                        var result = new
                        {
                            folderPath = selectedFolderPath,
                            folderName = directoryInfo.Name,
                            parentPath = directoryInfo.Parent?.FullName ?? string.Empty
                        };

                        var jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(result);
                        return ApiResponse.Success(jsonResult, "文件夹选择成功");
                    }
                    else
                    {
                        return ApiResponse.Fail("用户取消了文件夹选择");
                    }
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"打开文件夹对话框失败: {ex.Message}");
            }
        }

#endregion

#region 设备类型配置
        /// <summary>
        /// 根据连接方式，获取端口加载设备类型(类似plc等设备)
        /// </summary>
        public object GetPortLoadDeviceType(object param)
        {
            if (param == null)
            {
                return ApiResponse.Fail("参数不能为空");
            }

            var connectionType = param.ToString();
            if (string.IsNullOrEmpty(connectionType))
            {
                return ApiResponse.Fail("连接类型不能为空或空字符串");
            }

            var deviceTypes = DeviceRegisterConfigManager.GetDeviceTypesByConnectionType(connectionType);
            // 需要将数组转换为json字符串
            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(deviceTypes);
            return ApiResponse.Success(jsonString);
        }

        /// <summary>
        /// 根据设备id，获取端口加载设备的寄存器
        /// </summary>
        public object GetPortLoadDeviceRegisters(object param)
        {
            if (param == null)
            {
                return ApiResponse.Fail("参数不能为空");
            }

            var deviceId = param.ToString();
            if (string.IsNullOrEmpty(deviceId))
            {
                return ApiResponse.Fail("设备ID不能为空或空字符串");
            }

            var registers = DeviceRegisterConfigManager.GetRegistersByDeviceId(deviceId);
            // 需要将数组转换为json字符串
            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(registers);
            return ApiResponse.Success(jsonString);
        }

        public object GetVarRegistersTypeOptions(object param)
        {
            if (param == null)
            {
                return ApiResponse.Fail("参数不能为空");
            }

            var deviceId = param.ToString();
            if (string.IsNullOrEmpty(deviceId))
            {
                return ApiResponse.Fail("设备ID不能为空或空字符串");
            }

            int id = Convert.ToInt32(deviceId);

            var registers = DeviceRegisterConfigManager.GetRegistersByDeviceType(id);
            // 只获取Name字段，存到list中，并转成json
            var nameList = registers.Select(r => r.Name).ToList();
            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(nameList);
            return ApiResponse.Success(jsonString);
        }
#endregion

#region HJ212Code配置
        public object GetVarHJ212CodeSheetList(object param)
        {
            var nameList = DeviceHJ212Code.GetSheetNameList();
            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(nameList);
            return ApiResponse.Success(jsonString);
        }

        public object GetVarHJ212CodeSheetContent(object param)
        {
            if (param == null)
            {
                return ApiResponse.Fail("参数不能为空");
            }

            var sheetName = param.ToString();
            if (string.IsNullOrEmpty(sheetName))
            {
                return ApiResponse.Fail("表格名称不能为空或空字符串");
            }

            var sheet = DeviceHJ212Code.GetSheetByName(sheetName);
            if (sheet == null || sheet.Parameters == null)
            {
                return ApiResponse.Fail("未找到对应的表格或表格内容为空");
            }

            // 转换为JSON数组格式
            var objectArray = sheet.Parameters.Select(v => new
            {
                code = v.Code,
                chineseName = v.ChineseName,
                originalCode = v.OriginalCode,
                concentrationUnit = v.DefaultMeasurement,
                emissionUnit = v.DefaultUnit,
                concentrationDataType = v.DefaultDataType,
            }).ToArray();

            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(objectArray);
            return ApiResponse.Success(jsonString);
        }
#endregion

#region Oray远程控制
        public object GetOrayGetSn(object param)
        {
            return _networkManager._orayManager.GetOrayGetSn(param);
        }

        public object GetOrayRestart(object param)
        {
            return _networkManager._orayManager.GetOrayRestart(param);
        }
        
        public object GetOrayReset(object param)
        {
            return _networkManager._orayManager.GetOrayReset(param);
        }
        
        public object GetOrayStart(object param)
        {
            return _networkManager._orayManager.GetOrayStart(param);
        }
        
        public object GetOrayStop(object param)
        {
            return _networkManager._orayManager.GetOrayStop(param);
        }
        
        public object GetOrayStatus(object param)
        {
            return _networkManager._orayManager.GetOrayStatus(param);
        }
        #endregion

#region HJ212系统类型
    public object GetHJ212SystemType(object param)
    {
        return _networkManager.GetHJ212SystemType(param);
    }
 #endregion

#region MQTT配置
    public object GetMqttUIConfig(object param)
    {
        // 需要将MqttUIConfig.AllConfigData转换为json字符串
        var jsonString = JsonConvert.SerializeObject(MqttUIConfig.AllConfigData);
        // 需要将Topic、Payload、NetworkCard、ServerType的name字段分别转换为json数组
        var topicList = MqttUIConfig.AllConfigData?.Topic.Select(t => t.Name).ToList();
        var payloadList = MqttUIConfig.AllConfigData?.Payload.Select(p => p.Name).ToList();
        var networkCardList = MqttUIConfig.AllConfigData?.NetworkCard.Select(n => n.Name).ToList();
        var serverTypeList = MqttUIConfig.AllConfigData?.ServerType.Select(s => s.Name).ToList();
        var aliCloudTypeList = MqttUIConfig.AllConfigData?.AliCloudType.Select(a => a.Name).ToList();
        // 将topicList、payloadList、networkCardList、serverTypeList作为字段，组成一个json对象
        var config = new
        {
            Topic = topicList?.ToArray(),
            Payload = payloadList?.ToArray(),
            NetworkCard = networkCardList?.ToArray(),
            ServerType = serverTypeList?.ToArray(),
            AliCloudType = aliCloudTypeList?.ToArray()
        };
        // 将config转换为json字符串
        var configJsonString = JsonConvert.SerializeObject(config);
        return ApiResponse.Success(configJsonString);
    }
#endregion

#region DLT645配置
        public object GetDlt645Items(object param)
        {
            var itemNames = Dlt645Config.GetAllItemNames();
            // 如果param是空，则使用itemNames的第一个
            if (param == null)
            {
                param = itemNames.FirstOrDefault() ?? string.Empty;
            }

            var itemName = param.ToString();
            if (string.IsNullOrEmpty(itemName))
            {
                return ApiResponse.Fail("项目名称不能为空或空字符串");
            }

            var typeNames = Dlt645Config.GetTypeNamesByItemName(itemName);
            // 需要把itemNames和typeNames组成一个json对象
            var config = new
            {
                ruleCategories = itemNames,
                ruleIds = typeNames
            };
            var jsonString = JsonConvert.SerializeObject(config);
            return ApiResponse.Success(jsonString);
        }
#endregion

#region 检查更新
         public object CheckForUpdates(object param)
         {
             try
             {
                 // 解析参数获取更新URL
                 string updateUrl = "";
                 // 创建版本检查实例，VersionCheckUpate会自动从配置文件读取URL
                 var versionChecker = new VersionCheckUpate(updateUrl);
                 
                 // 执行版本检查
                 var result = versionChecker.CheckForUpdates(updateUrl);
                 
                 if (result.Success)
                 {
                     return ApiResponse.Success(true);
                 }
                 else
                 {
                     return ApiResponse.Fail(result.Message, "更新失败！！！");
                 }
             }
             catch (Exception ex)
             {
                 return ApiResponse.Fail($"检查更新时发生异常: {ex.Message}");
             }
         }

        public object GetVersionInfo(object param)
        {
            try
            {
                // 解析参数获取更新URL
                string updateUrl = "";
                // 创建版本检查实例
                var versionChecker = new VersionCheckUpate(updateUrl);
        
                // 使用SimpleCheckForUpdates避免弹出默认对话框
                var result = versionChecker.SimpleCheckForUpdates();
        
                // 构造返回结果
                var responseData = new
                {
                    success = result.Success,
                    hasUpdate = result.HasUpdate,
                    message = result.Message,
                    currentVersion = result.CurrentVersion,
                    latestVersion = result.LatestVersion,
                    downloadUrl = result.DownloadUrl,
                    changeLog = result.ChangeLog
                };
                
                var jsonString = JsonConvert.SerializeObject(responseData);
                if (result.Success)
                {
                    return ApiResponse.Success(jsonString);
                }
                else
                {
                    return ApiResponse.Fail(result.Message, responseData);
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"检查更新时发生异常: {ex.Message}");
            }
        }
        #endregion

#region Lua脚本
        public object RunLuaScript(object param)
        {
            // 如果param是空，则使用itemNames的第一个
            if (param == null)
            {
                return ApiResponse.Fail("参数不能为空");
            }

            try
            {
                string script = param.ToString() ?? "";
                Lua lua = new Lua();
                lua.DoString(script);
                var result = lua.DoString(script);
                if (result == null)
                {
                    return ApiResponse.Fail("执行Lua脚本失败");
                }
                var jsonString = JsonConvert.SerializeObject(result);
                return ApiResponse.Success(jsonString);                
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"执行Lua脚本时发生异常: {ex.Message}");
            }

        }
        #endregion

#region 登录
        public object ValidateUserLogin(object param)
        {
            // 如果param是空，则使用itemNames的第一个
            if (param == null)
            {
                return ApiResponse.Fail("参数不能为空");
            }

            try
            {
                string jsonParam = param.ToString() ?? "";
                // 需要在json中获取用户名和密码
                var json = JsonConvert.DeserializeObject<dynamic>(jsonParam);
                if (json == null)
                {
                    return ApiResponse.Fail("参数反序列化失败");
                }
                // 获取用户名和密码
                string? username = json.TryGetValue("username", out JToken? usernameValue) ? usernameValue?.ToString() : "";
                string? password = json.TryGetValue("password", out JToken? passwordValue) ? passwordValue?.ToString() : "";

                // 获取url
                var url = _networkManager.GetLoginUrl();
                if (string.IsNullOrEmpty(url))
                {
                    return ApiResponse.Fail("登录失败,url不能为空");
                }

                var result = HttpManager.Post(url, jsonParam);
                string content = result.Content ?? "";

                var jsonObj = JObject.Parse(content);
                if (jsonObj == null)
                {
                    return ApiResponse.Fail("登录失败,jsonObj不能为空");
                }
                
                // 提取顶级code字段
                var code = jsonObj["code"]?.ToString() ?? "";
                
                // 提取data对象中的token
                var dataObj = jsonObj["data"] as JObject;
                var token = dataObj?["token"]?.ToString() ?? "";

                if (result.IsSuccessful && code == "00000" && token != null)
                {
                    // 将token保存到本地
                    NetworkConfig.Instance.SetRemoteTransToken(token);
                    return ApiResponse.Success("登录成功");
                }
                else
                {
                    return ApiResponse.Fail("登录失败");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"登录时发生异常: {ex.Message}");
            }

        }
        #endregion

 #region 远程透传
        public object RemoteTransGetProductList(object param)
        {
            return _remoteTransManager.GetProductList(param);
        }
        public object RemoteTransGetDevicesList(object param)
        {
            return _remoteTransManager.GetDevicesList(param);
        }
        public object RemoteTransGetTransPorts(object param)
        {
            return _remoteTransManager.GetTransPortList(param);
        }
        public object RemoteTransGetDeviceDetailList(object param)
        {
            return _remoteTransManager.GetDeviceDetailList(param);
        }
        public object RemoteTransConnectSerial(object param)
        {
            return _remoteTransManager.ConnectSerial(param);
        }
        public object RemoteTransStart(object param)
        {
            return _remoteTransManager.Start(param);
        }
        public object RemoteTransListen(object param)
        {
            return _remoteTransManager.Listen(param);
        }
        public object RemoteTransGetTargetPort(object param)
        {
            return _remoteTransManager.GetTargetPort(param);
        }
        public object RemoteTransPortTypeSel(object param)
        {
            return _remoteTransManager.PortTypeSel(param);
        }
#endregion

#region 变量调试
        public object ReadRemoteMonitorVariant(object param)
        {
            return _networkManager.ReadRemoteMonitorVariant(param);
        }

        public object WriteRemoteMonitorVariant(object param)
        {
            return _networkManager.WriteRemoteMonitorVariant(param);
        }
#endregion


#region 打开链接
        public object OpenExternalBrowserLink(object param)
        {
            if (param == null)
            {
                return ApiResponse.Fail("参数不能为空");
            }

            string jsonParam = param.ToString() ?? "";
            var json = JsonConvert.DeserializeObject<dynamic>(jsonParam);
            if (json == null)
            {
                return ApiResponse.Fail("参数反序列化失败");
            }
            string? url = json.TryGetValue("url", out JToken? urlValue) ? urlValue?.ToString() : "";
            string? type = json.TryGetValue("type", out JToken? typeValue) ? typeValue?.ToString() : "";
            if (string.IsNullOrEmpty(url))
            {
                return ApiResponse.Fail("url不能为空");
            }

            // 打开浏览器
            try
            {   
                switch (type)
                {
                    case "register":
                        url = NetworkConfig.Instance.GetRegisterAccountUrl();
                        break;
                    case "file":
                        break;
                    case "help-doc":
                        url = NetworkConfig.Instance.GetHelpDocUrl();
                        break;
                    case "learning-platform":
                        url = NetworkConfig.Instance.GetLearningPlatformUrl();
                        break;   
                    case "download":
                        url = NetworkConfig.Instance.GetDownloadUrl();
                        break;
                    case "fireware":
                        url = NetworkConfig.Instance.GetFirewareUrl();
                        break;
                    case "api-doc":
                        url = NetworkConfig.Instance.GetApiDocUrl();
                        break;
                    case "quick-start":
                        url = NetworkConfig.Instance.GetQuickStartUrl();
                        break;
                    case "online-support":
                        url = NetworkConfig.Instance.GetOnlineSupportUrl();
                        break;                     
                }
                var psi = new System.Diagnostics.ProcessStartInfo
                {
                    FileName = url,
                    UseShellExecute = true
                };
                System.Diagnostics.Process.Start(psi);
            }
            catch (Exception)
            {
                // 如果上面的方法失败，尝试使用平台特定的方法
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    url = url.Replace("&", "^&");
                    Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Process.Start("xdg-open", url);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    Process.Start("open", url);
                }
                else
                {
                    throw;
                }
            }
            return ApiResponse.Success("打开链接成功");
        }
#endregion
    }

    public class CefSharpNative
    {
        private readonly NativeManager _nativeManager;

        public CefSharpNative(Control? invokeControl = null) // Add nullable annotation to allow null values  
        {
            _nativeManager = new NativeManager(invokeControl ?? new Control()); // Provide a default non-null Control instance if null is passed  
        }

        public Task<object?> CallNativeMethod(string methodName, object param, object? deviceId = null)
        {
            var type = _nativeManager.GetType();
            var method = type.GetMethod(methodName, new[] { typeof(object) });
            if (method == null)
            {
                return Task.FromResult<object?>(ApiResponse.NotFound());
            }

            var result = method.Invoke(_nativeManager, new[] { param });
            // 如果本来就是 Task<object?>，直接返回    
            if (result is Task<object?> taskObj)
                return taskObj;
            // 否则包一层 Task    
            return Task.FromResult<object?>(result);
        }
    }
}
